package Part2_TCP;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * ClassName: Test2
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.04.26 21:49
 */
public class Test2 {
    @Test
    public void client() throws IOException {

        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        Socket socket = new Socket(inetAddress,8989);


        File file = new File("650.jpg");
        FileInputStream fis = new FileInputStream(file);

        OutputStream outputStream = socket.getOutputStream();

        byte[] buffer1 = new byte[1024];
        int len;
        while ((len=fis.read(buffer1))!=-1){
            outputStream.write(buffer1,0 ,len);
        }

        //客户端表明不在发送数据，否则一直在循环中等待
        socket.shutdownOutput();
        System.out.println("文件传输结束");

        //接收服务端消息
        InputStream inputStream = socket.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//写入baos中维护的数组中
        byte[] buffer2 = new byte[5];
        int len2;
        while ((len2 = inputStream.read(buffer2)) != -1){
            baos.write(buffer2, 0 , len2);
        }
        System.out.println(baos.toString());

        baos.close();
        inputStream.close();
        outputStream.close();
        fis.close();
        socket.close();
    }

    @Test
    public void server() throws IOException{

        //创建ServerSocket
        ServerSocket serverSocket = new ServerSocket(8989);

        //接受来自于客户端的Socket
        Socket socket = serverSocket.accept();

        //socket创建输入流
        InputStream inputStream = socket.getInputStream();

        File file = new File("650_copy_new.png");
        FileOutputStream fos = new FileOutputStream(file);

        byte[] buffer = new byte[1024];
        int len;
        while ((len=inputStream.read(buffer))!=-1){
            fos.write(buffer,0 ,len);
        }
        System.out.println("文件传输结束");


        //服务端发送消息给客户端
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write("复制成功".getBytes(StandardCharsets.UTF_8));

        outputStream.close();
        fos.close();
        inputStream.close();
        socket.close();
        serverSocket.close();
    }
}
